//
//  StatusListViewModel.swift
//  Weibo
//
//  Created by 冯童童 on 16/1/22.
//  Copyright © 2016年 冯童童. All rights reserved.
//

import UIKit
import AFNetworking

class StatusListViewModel: NSObject {

    var statuses = [Status]()
    func loadHomeData(isPulling: Bool, finished : (isSuccess : Bool) -> ()) {
        
        let urlString = "2/statuses/home_timeline.json"
        guard let token = UserAccountViewModel().token else {
            print("用户暂未登录")
            finished(isSuccess: false)
           // SVProgressHUD.showErrorWithStatus("请重写登录")
            return
        }
        var parameters = ["access_token" : token]
        
        var since_id : Int64 = 0
        var max_id : Int64 = 0
        if isPulling {
            max_id = self.statuses.last?.id ?? 0
        }else {
            since_id = self.statuses.first?.id ?? 0
        }
        
        //    let since_id = self.statuses.first?.id ?? 0
        //    let max_id = self.statuses.last?.id ?? 0
        
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        NetworkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            
            if error != nil {
                finished(isSuccess: false)
                return
            }
            
          
            guard let array = dict!["statuses"] as? [[String : AnyObject]] else {
                
                // SVProgressHUD.showErrorWithStatus(AppErrorTip)
                finished(isSuccess: false)
                
                print("数据结构错误")
                return
            }
            var tempArray = [Status]()
            for item in array {
                let s = Status(dict: item)
                //  print(s)
                tempArray.append(s)
            }
            
            if since_id > 0 {
                
                self.statuses = tempArray + self.statuses
            }else if max_id > 0 {
                self.statuses += tempArray
                //self.indicatorView.stopAnimating()
            }else {
                self.statuses = tempArray
            }
            //print(tempArray.count)
            //self.tableView.reloadData()
            // finished(statuses: tempArray)
            finished(isSuccess: true)

            
        }
 
    }
}
